//
//  Log.swift
//  TLCLockDemo
//
//  Created by run on 2024/7/6.
//

import CocoaLumberjackSwift
import Foundation

struct Log {
    private static let openLog: Bool = true

    static let fileLogger: DDFileLogger = {
        let logger = DDFileLogger()
        logger.rollingFrequency = 60 * 60 * 24 * 2 // 2天
        logger.logFileManager.maximumNumberOfLogFiles = 7

        return logger
    }()

    static func initLog() {
        guard openLog else { return }

        let logger = DDOSLogger.sharedInstance
        logger.logFormatter = CustomLogFormatter()
        
        DDLog.add(logger)
        DDLog.add(fileLogger)
    }

    static func debug(_ message: String) {
        guard openLog else { return }
        // print("[\(Date().yMds)]DEBUG:\(message)")
        DDLogDebug(DDLogMessageFormat(stringLiteral: message))
    }

    static func info(_ message: String) {
        guard openLog else { return }
        // print("[\(Date().yMds)]INFO:\(message)")
        DDLogInfo(DDLogMessageFormat(stringLiteral: message))
    }

    static func warning(_ message: String) {
        guard openLog else { return }
        // print("[\(Date().yMds)]ERROR:\(message)")
        DDLogWarn(DDLogMessageFormat(stringLiteral: message))
    }

    static func error(_ message: String) {
        guard openLog else { return }
        // print("[\(Date().yMds)]ERROR:\(message)")
        DDLogError(DDLogMessageFormat(stringLiteral: message))
    }
}

private class CustomLogFormatter: NSObject, DDLogFormatter {
    override init() {
        super.init()
    }

    func format(message logMessage: DDLogMessage) -> String? {
        let dateAndTime = logMessage.timestamp.yMdss
        let logFlag: String

        switch logMessage.flag {
        case .error:
            logFlag = "ERROR"
        case .warning:
            logFlag = "WARNING"
        case .info:
            logFlag = "INFO"
        case .debug:
            logFlag = "DEBUG"
        case .verbose:
            logFlag = "VERBOSE"
        default:
            logFlag = "UNKNOWN"
        }

        return "\(dateAndTime) |\(logFlag)| \(logMessage.message)"
    }
}
